<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Autoplay } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/autoplay'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* ---- */
const user = reactive({
  info: '',
  cname: '服务团队',
  btnTxt: '婚介交友',
  marryRegId: undefined,
  telphone: proxy.$telPhone,
  wechat_img: proxy.$imgEwm,
  // ----
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon
})
// ----
const forAdvs = ref([])
const forFreeAdvs = 3 / 1
const setTrueStyleAdvs = ref({})
const forAutoplay = {
  delay: 5000,
  disableOnInteraction: false
}
const modules = [Autoplay]
// ----
const tbtns = ref([])
// ----
const forFree = 9 / 5
const setTrueStyle = ref({})
// ----
const moveTime = 50
let showMarquee = null
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const preImg = ref()
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const getTrueStyleAdvs = () => {
  if (proxy.$refs.forTrueWidthAdvs) {
    const imgEL = proxy.$refs.forTrueWidthAdvs
    const imgRatio = forFreeAdvs
    setTrueStyleAdvs.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
const getTrueStyle = () => {
  if (proxy.$refs.forTrueWidth) {
    const imgEL = proxy.$refs.forTrueWidth
    const imgRatio = forFree
    setTrueStyle.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
// ----
const setMarquee = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    const forLi = el.innerHTML
    if (Number(el.firstChild.offsetWidth) > Number(el.offsetWidth)) {
      el.innerHTML = forLi + forLi
      showMarquee = setInterval(marqueefun, moveTime)
    }
  }
}
const marqueefun = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    if (Number(el.lastChild.offsetWidth) <= Number(el.scrollLeft)) {
      el.scrollLeft = el.scrollLeft - el.firstChild.offsetWidth
    } else {
      el.scrollLeft = el.scrollLeft + 1
    }
  }
}
const stopRolling = () => {
  if (showMarquee) {
    clearInterval(showMarquee)
    showMarquee = null
  } else {
    showMarquee = setInterval(marqueefun, moveTime)
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  if (Number(Object.keys(logUser).length) > 0) {
    // --是否婚介交友报名--
    await proxy.$http.get('marriage-frm/index', {
      params: {
        'MarriageFrmSearch[dealer_id]': logUser.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: 1,
        PageSize: 1
      }
    }).then((res) => {
      if (Number(res.items.length) > 0) user.marryRegId = res.items[0].id
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // --获取信息--
  const termData = forSys.filter((item) => { return String(item.name) === 'market_terms' })
  if (Number(termData.length) === 1) {
    await proxy.$Myfun.getJsonData(termData[0].value, (resJson) => {
      const curRes = resJson[0]
      // ----
      if (curRes.remark && Number(curRes.remark.length) > 0) user.info = proxy.$Myfun.setText(curRes.remark)
      if (curRes.telphone && Number(curRes.telphone.length) > 0) user.telphone = proxy.$Myfun.setText(curRes.telphone)
      if (curRes.ewm && Number(curRes.ewm.length) > 0) user.wechat_img = curRes.ewm[0].image
      // ----
      user.title = proxy.$Myfun.setText(curRes.title)
      if (curRes.share_title) user.share_title = proxy.$Myfun.setText(curRes.share_title)
      if (curRes.share_desc) user.share_desc = proxy.$Myfun.setText(curRes.share_desc)
      if (curRes.share_img && Number(curRes.share_img.length) > 0) user.share_icon = curRes.share_img[0].image
    })
  }
  // ----
  if (user.info) nextTick(() => { setMarquee() })
  // --获取服务团队顶部广告--
  const forImgData = {
    params: {
      'AdsSearch[type]': 11,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('ads/index', forImgData)
  ]).then(proxy.$Axios.spread((imgData) => {
    const advItems = []
    imgData.items.forEach((item) => {
      const forAdv = {
        id: item.id,
        image: '',
        link: item.link_url
      }
      proxy.$Myfun.getJsonData(item.img_json, (resJson) => {
        if (Number(resJson.length) > 0) forAdv.image = resJson[0].image
      })
      advItems.push(forAdv)
    })
    forAdvs.value = advItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  tbtns.value = [{
    show: true,
    icon: 'fal fa-house-chimney xw-color-11',
    style: 'TBX-icon xw-radius-round xw-shadow xw-bg-white',
    callback: () => { proxy.$Myfun.openPage(proxy, 'push', 'UcenTer') }
  }, {
    show: true,
    icon: 'fal fa-phone-volume xw-color-11',
    style: 'TBX-icon xw-radius-round xw-shadow xw-bg-white',
    callback: () => {
      let options = {
        title: proxy.$Global.layer.titleTwo + user.telphone,
        content: proxy.$Global.layer.conEver,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnAsk,
          class: 'xw-color-24',
          callback: () => { window.location.href = 'tel:' + user.telphone }
        }]
      }
      if (user.wechat_img) {
        options = {
          title: proxy.$Global.layer.titleThree,
          content: '<div style="padding: 0 2.4rem;"><img src="' + user.wechat_img + '" style="width: 100%;"/></div>',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: proxy.$Global.layer.btnAsk,
            class: 'xw-color-24',
            callback: () => { window.location.href = 'tel:' + user.telphone }
          }]
        }
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
    }
  }]
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // --设置微信分享功能--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'ads/index',
    forData: {
      params: {
        'AdsSearch[type]': 12,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let advItem = {}
    proxy.$Myfun.getJsonData(item.img_json, (resJson) => {
      advItem = {
        id: item.id,
        link: proxy.$Myfun.setText(item.link_url),
        // ----
        msrc: resJson[0].image,
        src: resJson[0].image,
        width: resJson[0].width,
        height: resJson[0].height,
        alt: ''
      }
    })
    // ----
    newItems.push(advItem)
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item, event, index) => {
  switch (Number(type)) {
    case 1: {
      if (item && Number(item.length) > 0) window.location.href = item
      break
    }
    case 2: {
      const options = {
        title: '万域商友会婚介交友',
        content: '<div style="line-height: 3rem; font-size: 1.7rem;">无费用，精准介绍为你喜结良缘<br/>有温度，贴心服务确保门当户对</div>',
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: '我要报名',
          class: 'xw-color-24',
          callback: () => { proxy.$Myfun.openPage(proxy, 'push', 'MarryReg', { id: user.marryRegId }) }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 3: {
      if (Number(item.length) > 0) {
        const curEL = event.currentTarget
        const options = {
          actElement: curEL,
          addopt: {
            index: Number(index) || 0,
            loop: true,
            dataSource: item
          }
        }
        proxy.$Myfun.isIndepth(preImg.value, 'openPhotoSwipe', options)
      }
      break
    }
    case 4: {
      item.callback && item.callback()
      break
    }
  }
}

/* ---- */
onMounted(() => {
  setTimeout(() => { getTrueStyleAdvs() }, 100)
  // ----
  setTimeout(() => { getTrueStyle() }, 100)
  // ----
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <!---->
        <div class="list-li-adv"><div ref="forTrueWidthAdvs"></div></div>
        <swiper :modules="modules" :autoplay="forAutoplay" :style="setTrueStyleAdvs" v-if="Number(forAdvs.length) > 0">
          <swiper-slide class="xw-act" v-for="(item, index) in forAdvs" @click="getAuditFun(1, item.link)"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></swiper-slide>
        </swiper>
        <!---->
        <div class="INIT-spons xw-flex xw-flex-align" v-if="user.info">
          <em class="far fa-volume-up xw-color-12"></em>
          <div class="forMarquee xw-flex-W1">
            <div ref="forMarquee" class="FMQ-con xw-act xw-flex xw-flex-align" @click="stopRolling">
              <ul class="xw-flex-W1">
                <li>{{user.info}}</li>
              </ul>
            </div>
          </div>
        </div>
        <div class="INIT-lm xw-flex xw-flex-align xw-flex-justify">
          <div class="xw-flex-W1">
            <div class="INIT-title xw-color-11 xw-Lfg">{{user.cname}}</div>
          </div>
          <span class="INIT-submit xw-btn xw-WBlue" @click="getAuditFun(2)">{{user.btnTxt}}</span>
        </div>
        <ul class="list-pic xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items" @click="getAuditFun(3, items, $event, index)"><div class="xw-act" :style="setTrueStyle">
            <div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.src + ')' }"></div>
          </div></li>
          <div class="list-li"><div ref="forTrueWidth"></div></div>
        </ul>
      </div>
    </div>
    <div class="tabfix">
      <template v-for="(item, index) in tbtns">
        <a class="xw-flex xw-flex-center xw-flex-column" :class="item.style" @click="getAuditFun(4, item)" v-if="item.show">
          <em :class="item.icon" v-if="item.icon"></em><span v-html="item.name" v-if="item.name"></span>
        </a>
      </template>
    </div>
    <preImg-view ref="preImg"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.INIT-spons { padding: 1rem 0 0 1rem; }
.INIT-lm { padding: 1rem 1rem 0; }
.INIT-title { padding: 0 0 0 1.4rem; font-size: 1.7rem; font-weight: bold; }
.INIT-title:before { top: 0.2rem; bottom: 0.2rem; width: 0.8rem; background: #ff5722; }

/* ---- */
.list-pic li { position: relative; margin: 1.2rem 1rem 0; overflow: hidden; }
.list-li { margin: 0 1rem; }

/* ---- */
.forMarquee { height: 100%; padding: 0 1rem; }
.FMQ-con { height: 100%; }
.FMQ-con ul { white-space: nowrap; overflow: hidden; }
.FMQ-con li { display: inline-block; }
</style>